﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Photon.SocketServer;
using Common;
using Common.Tools;
using Common.Model;

using MyGameServer.Manager;
using MyGameServer.Model;
using System.IO;
using System.Xml.Serialization;

namespace MyGameServer.Handler
{
    class ExitRoomHandler : BaseHandler
    {
        public ExitRoomHandler()
        {
            OpCode = OperationCode.ExitRoom;
        }
        public override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters, ClientPeer peer)
        {
            //int roomId = (int)DictTool.GetValue<byte, object>(operationRequest.Parameters, (byte)ParameterCode.JoinRoom);
            //Room room = Functions.GetRoom(MyGameServer.Instance.roomList, roomId); // 进入的房间
            //CommonUser user = new CommonUser(); // 玩家自己
            //user.id = peer.uuid; // 玩家id
            //user.username = peer.username; // 玩家姓名
            //room.playerList.Add(user); // 把自己放到房间里


            Room room = Functions.RemovePlayerFromRoomList(MyGameServer.Instance.roomList, peer.uuid);
            
            OperationResponse response = new OperationResponse(operationRequest.OperationCode);

            //Dictionary<byte, object> data = new Dictionary<byte, object>();

            //StringWriter sw_room = new StringWriter();
            //XmlSerializer serializer_room = new XmlSerializer(typeof(Room));
            //serializer_room.Serialize(sw_room, room);
            //sw_room.Close();
            //string roomString = sw_room.ToString();

            //data.Add((byte)ParameterCode.JoinRoom, roomString);
            
            
            //response.Parameters = data;
            peer.SendOperationResponse(response, sendParameters);


            //广播
            foreach (var ntfPeer in MyGameServer.Instance.peerList)
            {
                if (string.IsNullOrEmpty(ntfPeer.username) == false)
                {
                    bool isInRoom = Functions.IsPlayerInRoom(room, ntfPeer.uuid);
                    if (isInRoom)
                    {
                        EventData ed = new EventData((byte)EventCode.ExitRoom);
                        Dictionary<byte, object> dataEvent = new Dictionary<byte, object>();

                        //Room ntfRoom = new Room();
                        //user.id = peer.uuid;
                        //user.readyState = readyState;
                        string roomString = Functions.ObjectToXmlString<Room>(room);
                        dataEvent.Add((byte)ParameterCode.ExitRoom, roomString);

                        ed.Parameters = dataEvent;
                        ntfPeer.SendEvent(ed, sendParameters);
                    }
                }
            }
        }
    }
}
